<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.race()</title>
</head>
<body>
    <h1>Promise.race()</h1>
    <h2>只要有一个Promise实例率先改变状态，就会返回那个Promise的结果</h2>

    <script>
        // 基本用法
        const p1 = new Promise(resolve => setTimeout(() => resolve('one'), 500));
        const p2 = new Promise(resolve => setTimeout(() => resolve('two'), 100));
        const p3 = new Promise(resolve => setTimeout(() => resolve('three'), 300));

        Promise.race([p1, p2, p3])
            .then(value => {
                console.log(value); // 'two'，因为p2最快
            });

        // 实际应用：请求超时
        function requestWithTimeout(url, timeout = 5000) {
            const request = fetch(url);
            const timeoutPromise = new Promise((resolve, reject) => {
                setTimeout(() => reject(new Error('请求超时')), timeout);
            });

            return Promise.race([request, timeoutPromise]);
        }

        // 使用示例
        // requestWithTimeout('https://api.example.com/data', 3000)
        //     .then(response => response.json())
        //     .then(data => console.log(data))
        //     .catch(error => console.log(error.message));
    </script>
</body>
</html> 